use regex::Regex;
use text_colorizer::*;

#[derive(Debug)]
struct Argument {
    target: String,
    replacement: String,
    filename: String,
    output: String,
}

fn print_usage() {
    eprintln!(" {} - change occurrences of one string into another", "quickreplace".green());
    eprintln!("usage: quickreplace <target> <replacement> <filename> <output>");
}

fn parse_args() -> Argument {
    let args: Vec<String> = std::env::args().skip(1).collect();
    if args.len() != 4 {
        print_usage();
        eprintln!("{}: expected 4 arguments, got {}", "Error".red().bold(), args.len());
        std::process::exit(1);
    }
    Argument {
        target: args[0].clone(),
        replacement: args[1].clone(),
        filename: args[2].clone(),
        output: args[3].clone(),
    }
}

fn replace(target: &str, replacement:&str, text:&str) -> Result<String, regex::Error>{
    let regex = Regex::new(target)?;
    Ok(regex.replace_all(text, replacement).to_string())
}

fn main() {
    println!("Hello, world!");
    let args = parse_args();
    println!("{:?}", args);
    let text = std::fs::read_to_string(&args.filename);
    let text = match text {
        Ok(t) => t,
        Err(e) => {
            eprintln!("{}: {}", "Error".red().bold(), e);
            std::process::exit(1);
        }
    };
    println!("{}: {} -> {}", "Replacing".green(), args.target, args.replacement);
    let replaced_text = replace(&args.target, &args.replacement, &text);
    let replaced_text = match replaced_text {
        Ok(t) => t,
        Err(e) => {
            eprintln!("{}: {}", "Error".red().bold(), e);
            std::process::exit(1);
        }
    };
    let wdata = std::fs::write(&args.output, &replaced_text);
    match wdata {
        Ok(_) => println!("{}: {}", "Success".green(), "replaced text written to file".green()),
        Err(e) => {
            eprintln!("{}: {}", "Error".red().bold(), e);
            std::process::exit(1);
        }
    };

}
